package com.hup.utils.commons.exception.parser;

import com.alibaba.fastjson.JSONException;
import com.hup.utils.commons.exception.ErrParserRegister;
import com.hup.utils.commons.exception.ExceptionMsgParser;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindException;

import java.util.ArrayList;
import java.util.List;

/**
 * 注册时,需要有以下依赖
 *
 * @author hugan
 * @date 2019/9/10
 * @apiNote 未完成
 */
public class WebApiAccessMsgParser implements ErrParserRegister {

    @Override
    public List<ExceptionMsgParser> getParsers() {
        ArrayList<ExceptionMsgParser> list = new ArrayList<>();
        list.add(new ApiArg());
        list.add(new Json());
        return list;
    }

    private static class ApiArg implements ExceptionMsgParser<Throwable> {
        @Override
        public boolean isMatch(Throwable e) {
            return e instanceof IllegalStateException
                    //MethodArgumentTypeMismatchException
                    || e instanceof TypeMismatchException
                    || e instanceof BindException;
        }

        @Override
        public String getMsg(Throwable e) {
            return "api入参异常";
        }
    }

    private static class Json implements ExceptionMsgParser<JSONException> {

        @Override
        public String getMsg(JSONException e) {
                /*
                JSONException源码分析: jo转对象时,如果对象中有多层对象嵌套,万一发生转换错误时,就会套了n层JSONException;
                所以不建议循环获取e.getCause();
                直接根据e.getMessage的日志进行解析:目前无非是 字符串转数字有异常
                 */
            String message = e.getMessage();
            int indexOf = message.indexOf('\"');
            if (message.contains("For input string") && indexOf != -1) {
                return "数字转换异常:" + message.substring(indexOf + 1, message.length() - 1);
            } else {
                return message;
            }
        }
    }

    //private static class TypeMismatch implements ExceptionMsgParser<HttpRequestMethodNotSupportedException> {
    //
    //    @Override
    //    public String getMsg(TypeMismatchException e) {
    //        return "api调用异常";
    //    }
    //}

    //private static class TypeMismatch implements ExceptionMsgParser<HttpMessageNotReadableException> {
    //
    //    @Override
    //    public String getMsg(HttpMessageNotReadableException e) {
    //        //spring层转换参数 时的异常,未到达项目代码的controller层中的,由HwExceptionHandler处理后到达这里
    //String msg = e.getMessage();
    //int indexOf;
    //        if ((indexOf = msg.indexOf(TAG_INT_ERR)) != -1) {
    //    int indexOfEd = msg.indexOf(':', indexOf);
    //    return "[整数]输入错误:" + msg.substring(indexOf + TAG_INT_ERR.length(), indexOfEd);
    //} else {
    //    //不需要用户看到错误消息
    //    return "数据或参数异常";
    //}
    //    }
    //}

}
